package com.khotyn.heresy.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.bean.PagedBean;
import com.khotyn.heresy.exception.IllegalUrlParamException;
import com.khotyn.heresy.service.CommentListService;

/**
 * 评论列表控制器
 * 
 * @author 黄挺
 * 
 */
@Controller
@RequestMapping("/commentList.html")
public class CommentListController {
	@Autowired
	private CommentListService commentListService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpSession session, HttpServletRequest request,
			@RequestParam(value = "pictureID", required = false) String pictureID, @RequestParam(value = "page", required = false) String pageStr) {
		try {
			validate(pictureID, pageStr);
		} catch (IllegalUrlParamException e) {
			return e.getErrorModel();
		}

		Integer userID = (Integer) session.getAttribute("userID");
		Integer page = Integer.parseInt(pageStr);

		PagedBean comments = commentListService.doService(pictureID, userID, page);
		return new ModelAndView("commentList", "comments", comments);
	}

	private void validate(String pictureID, String pageStr) throws IllegalUrlParamException {
		HeresyErrorMessage errorMessage = null;

		if (!NumberUtils.isDigits(pictureID) || !NumberUtils.isDigits(pageStr)) {
			errorMessage = new HeresyErrorMessage("非法的参数", "操作失败", "/Dragonfly/");
		}

		if (errorMessage != null) {
			throw new IllegalUrlParamException(errorMessage);
		}
	}
}
